﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Admin.NET.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Web;
using Furion.RemoteRequest.Extensions;
using Furion;
using Serilog;
using HttpMethod = System.Net.Http.HttpMethod;

namespace Admin.NET.Application
{
    /// <summary>
    /// 退货单服务
    /// </summary>
    [ApiDescriptionSettings("退货单", Name = "WmsGoodsReturnOrder", Order = 100)]
    [Route("api/[Controller]")]
    public class WmsGoodsReturnOrderService : IWmsGoodsReturnOrderService, IDynamicApiController, ITransient
    {
        private readonly IRepository<WmsGoodsReturnOrder,MasterDbContextLocator> _wmsGoodsReturnOrderRep;
        private readonly IRepository<SysDictType, MasterDbContextLocator> _sysDictTypeRep;
        private readonly IRepository<SysDictData, MasterDbContextLocator> _sysDictDataRep;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly static object _lock = new();
        private readonly IRepository<WmsGoodsReturnOrderDetails, MasterDbContextLocator> _wmsGoodsReturnOrderDetailsRep;
        private readonly IRepository<WmsOrderType, MasterDbContextLocator> _wmsOrderTypeRep;



        public WmsGoodsReturnOrderService(
            IRepository<WmsGoodsReturnOrder,MasterDbContextLocator> wmsGoodsReturnOrderRep
            ,IRepository<SysDictType, MasterDbContextLocator> sysDictTypeRep
            ,IRepository<SysDictData, MasterDbContextLocator> sysDictDataRep
            ,ISysExcelTemplateService sysExcelTemplateService
            , IRepository<WmsGoodsReturnOrderDetails, MasterDbContextLocator> wmsGoodsReturnOrderDetailsRep
            , IRepository<WmsOrderType, MasterDbContextLocator> wmsOrderTypeRep

        )
        {
            _wmsGoodsReturnOrderRep = wmsGoodsReturnOrderRep;
         _sysDictTypeRep = sysDictTypeRep;
         _sysDictDataRep = sysDictDataRep;
         _sysExcelTemplateService = sysExcelTemplateService;
            _wmsGoodsReturnOrderDetailsRep = wmsGoodsReturnOrderDetailsRep;
            _wmsOrderTypeRep = wmsOrderTypeRep;
        }

        /// <summary>
        /// 分页查询退货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<WmsGoodsReturnOrderOutput>> Page([FromQuery] WmsGoodsReturnOrderSearch input)
        {
            var wmsGoodsReturnOrders = await _wmsGoodsReturnOrderRep.DetachedEntities
                                     .Where(!string.IsNullOrEmpty(input.NO), u => EF.Functions.Like(u.NO, $"%{input.NO.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Vendorcode), u => EF.Functions.Like(u.Vendorcode, $"%{input.Vendorcode.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Vendorname), u => EF.Functions.Like(u.Vendorname, $"%{input.Vendorname.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Companyname), u => EF.Functions.Like(u.Companyname, $"%{input.Companyname.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.WarehouseKeepername), u => EF.Functions.Like(u.WarehouseKeepername, $"%{input.WarehouseKeepername.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.WarehouseCentername), u => EF.Functions.Like(u.WarehouseCentername, $"%{input.WarehouseCentername.Trim()}%"))
                                     .Where(input.GoodsReturnStatus != null, u => u.GoodsReturnStatus == input.GoodsReturnStatus)
                                     .OrderBy(PageInputOrder.OrderBuilder<WmsGoodsReturnOrderSearch>(input))
                                     .ProjectToType<WmsGoodsReturnOrderOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsGoodsReturnOrders;
        }

        /// <summary>
        /// 获取单据明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("PageDetail")]
        public async Task<PageResult<WmsGoodsReturnOrderDetailOutput>> PageDetail([FromQuery] GoodsReturnOrdePageDetailInput input)
        {
            var wmsOrders = await _wmsGoodsReturnOrderDetailsRep.DetachedEntities
                                     .Where(input.Id != null, u => u.OrderId == input.Id)
                                     .ProjectToType<WmsGoodsReturnOrderDetailOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsOrders;
        }

        /// <summary>
        /// 获取退货单(yigo系统)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("GetGoodsReturnOrder")]
        public async Task GetGoodsReturnOrder()
        {
            //获取退库单
            string url = App.Configuration["YiGoWebApi:QueryBackNotice"];
            var Billdate_S = DateTime.Now.AddDays(-15).ToString("yyyy-MM-dd");
            var Billdate_E = DateTime.Now.AddDays(15).ToString("yyyy-MM-dd");
            //写日志文件
            //Log.Error($"[TransferContainerCode][ContainerCode:{input.ContainerCode}][url:{url}]");
            var response = await url.SetHttpMethod(System.Net.Http.HttpMethod.Post)
                                    .SetBody(new Dictionary<string, object> {
                                            { "Billdate_S", Billdate_S },
                                            { "Billdate_E", Billdate_E},
                                    }, "application/json").PostAsStringAsync();
            var Data = response.FromJson<GetGoodsReturnOrderOutputByYiGo>();
            var wmsOrderType = await _wmsOrderTypeRep.FirstOrDefaultAsync(z => z.Name.Contains("退货出库"));
            foreach (var item in Data.Data)
            {
                item.Id = Yitter.IdGenerator.YitIdHelper.NextId();
                var wmsGoodsReturnOrder = item.Adapt<WmsGoodsReturnOrder>();
                var isExcit = await _wmsGoodsReturnOrderRep.AnyAsync(x => x.NO == item.NO);
                if (!isExcit)
                {
                    wmsGoodsReturnOrder.OrderLargeCategory = wmsOrderType != null ? wmsOrderType.Pid : 0;
                    wmsGoodsReturnOrder.OrderSubclass = wmsOrderType != null ? wmsOrderType.Id : 0;
                    await _wmsGoodsReturnOrderRep.InsertNowAsync(wmsGoodsReturnOrder);
                    foreach (var item1 in item.Dtls)
                    {
                        var WmsGoodsReturnOrderDetail = item1.Adapt<WmsGoodsReturnOrderDetails>();
                        WmsGoodsReturnOrderDetail.OrderId = item.Id;
                        await _wmsGoodsReturnOrderDetailsRep.InsertNowAsync(WmsGoodsReturnOrderDetail);
                    }
                }
            }
        }

        /// <summary>
        /// 退货下架接口(yigo系统)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("ReturnGoodsReturnOrder")]
        [UnifyResult(typeof(object))]
        [UnitOfWork]
        public async Task<object> ReturnGoodsReturnOrder([FromBody] ReturnGoodsReturnOrderInput input)
        {
            try
            {
                //创建指定名称的订单操作
                string url = App.Configuration["YiGoWebApi:CreateTXRe211"];
                //获取主单据
                var wmsGoodsReturnOrderModal = await _wmsGoodsReturnOrderRep.FirstOrDefaultAsync(x => x.Id == input.Id);
                if (wmsGoodsReturnOrderModal == null) throw Oops.Oh("单据信息不存在!");
                //改变主单据状态
                // 写日志文件
                Log.Error($"[InspectionDeclaration][单据号:{wmsGoodsReturnOrderModal.NO}][url:{url}]");

                var response = await url.SetHttpMethod(HttpMethod.Post)
                                        .SetBody(input, "application/json")
                                        .PostAsAsync<ReturnGoodsReturnOrderOutput>();
                // 写日志文件
                Log.Error($"[InspectionDeclaration][单据号:{wmsGoodsReturnOrderModal.NO}][response:{response.ToJson()}]");

                return XnRestfulResultProvider.RESTfulResult(response);
            }
            catch (Exception ex)
            {
                throw Oops.Oh(ex.Message);
            }
        }


        /// <summary>
        /// 不分页查询退货单列表
        /// </summary>
        /// <param name="input">退货单查询参数</param>
        /// <returns>(退货单)实例列表</returns>
        [HttpGet("listNonPage")]
        public async Task<List<WmsGoodsReturnOrderOutput>> ListNonPageAsync([FromQuery] WmsGoodsReturnOrderSearchNonPage input)
        {
            var pNO = input.NO?.Trim() ?? "";
            var pVendorcode = input.Vendorcode?.Trim() ?? "";
            var pVendorname = input.Vendorname?.Trim() ?? "";
            var pCompanyname = input.Companyname?.Trim() ?? "";
            var pWarehouseKeepername = input.WarehouseKeepername?.Trim() ?? "";
            var pWarehouseCentername = input.WarehouseCentername?.Trim() ?? "";
            var pGoodsReturnStatus = input.GoodsReturnStatus;
            var wmsGoodsReturnOrders = await _wmsGoodsReturnOrderRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(pNO), u => EF.Functions.Like(u.NO, $"%{pNO}%")) 
                .Where(!string.IsNullOrEmpty(pVendorcode), u => EF.Functions.Like(u.Vendorcode, $"%{pVendorcode}%")) 
                .Where(!string.IsNullOrEmpty(pVendorname), u => EF.Functions.Like(u.Vendorname, $"%{pVendorname}%")) 
                .Where(!string.IsNullOrEmpty(pCompanyname), u => EF.Functions.Like(u.Companyname, $"%{pCompanyname}%")) 
                .Where(!string.IsNullOrEmpty(pWarehouseKeepername), u => EF.Functions.Like(u.WarehouseKeepername, $"%{pWarehouseKeepername}%")) 
                .Where(!string.IsNullOrEmpty(pWarehouseCentername), u => EF.Functions.Like(u.WarehouseCentername, $"%{pWarehouseCentername}%")) 
                .Where(pGoodsReturnStatus != null, u => u.GoodsReturnStatus == pGoodsReturnStatus)
            .OrderBy(PageInputOrder.OrderNonPageBuilder(input))
            .ProjectToType<WmsGoodsReturnOrderOutput>()
            .ToListAsync();
            return wmsGoodsReturnOrders;
        }


        /// <summary>
        /// 增加退货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add(AddWmsGoodsReturnOrderInput input)
        {
            var wmsGoodsReturnOrder = input.Adapt<WmsGoodsReturnOrder>();
            await _wmsGoodsReturnOrderRep.InsertAsync(wmsGoodsReturnOrder);
        }

        /// <summary>
        /// 删除退货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteWmsGoodsReturnOrderInput input)
        {
            var wmsGoodsReturnOrder = await _wmsGoodsReturnOrderRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _wmsGoodsReturnOrderRep.DeleteAsync(wmsGoodsReturnOrder);
        }

        /// <summary>
        /// 更新退货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateWmsGoodsReturnOrderInput input)
        {
            var isExist = await _wmsGoodsReturnOrderRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var wmsGoodsReturnOrder = input.Adapt<WmsGoodsReturnOrder>();
            await _wmsGoodsReturnOrderRep.UpdateAsync(wmsGoodsReturnOrder,ignoreNullValues:true);
        }

        /// <summary>
        /// 获取退货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<WmsGoodsReturnOrderOutput> Get([FromQuery] QueryeWmsGoodsReturnOrderInput input)
        {
            return (await _wmsGoodsReturnOrderRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<WmsGoodsReturnOrderOutput>();
        }

        /// <summary>
        /// 获取退货单列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<WmsGoodsReturnOrderOutput>> List([FromQuery] WmsGoodsReturnOrderInput input)
        {
            return await _wmsGoodsReturnOrderRep.DetachedEntities.ProjectToType<WmsGoodsReturnOrderOutput>().ToListAsync();
        }    
         /// <summary>
        /// Excel模板导入退货单功能
        /// </summary>
        /// <param name="file">Excel模板文件</param>
        /// <param name="importExcelType">Excel导入方式</param>
        /// <returns>导入的记录数</returns>
        [HttpPost("fromExcel")]
        public async Task<int> FromExcelAsync(IFormFile file, [FromQuery] ImportExcelType importExcelType)
        {
            int size = 200;
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsGoodsReturnOrder", "v2");
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var keys = excelTemplate.UnionUniqueFields.Split(",") ?? Array.Empty<string>();
            for (var i = 0; i < keys.Length; i++) 
            {
                keys[i] = keys[i]?.Trim() ?? string.Empty;
            }
            ExcelUtil.FromExcel(file, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, out List<string> headers, out List<List<object?>> data, out string sheetName);
            List<WmsGoodsReturnOrderOutput> wmsGoodsReturnOrderList = DataConvertUtil.ToObjectList(headers, data, sheetName, keys, excelTemplate?.DataStartLine ?? 2, out Dictionary<string, WmsGoodsReturnOrderOutput> dict);
            List<Dictionary<string, object>> uniqueKeyValueDictList = wmsGoodsReturnOrderList.ParseUniqueKeyValueDictList(keys.ToList(), excelTemplate?.DataStartLine ?? 2, sheetName);
            var filters = DataConvertUtil.GetExpressionListByUniqueDict<WmsGoodsReturnOrder>(keys.ToList(), uniqueKeyValueDictList, size);
            var selectKeys = keys.ToList();
            if(!selectKeys.Contains("Id")) selectKeys.Add("Id");
            var selector = DataConvertUtil.GetSelectExpressionListByUniqueDict<WmsGoodsReturnOrder, WmsGoodsReturnOrderOutput>(selectKeys);
            List<WmsGoodsReturnOrder> updates = new();
            List<WmsGoodsReturnOrder> adds = new();

            lock (_lock)
            {
                foreach (var filter in filters)
                {
                    var wmsGoodsReturnOrderExistSubList = _wmsGoodsReturnOrderRep.Where(filter).Select(selector).ToList();
                    wmsGoodsReturnOrderExistSubList.ForEach(x => 
                    {
                        var k = DataConvertUtil.GetKey(x, keys);
                        if (dict.ContainsKey(k)) dict[k].Id = x.Id;
                    });
                }
                foreach (var wmsGoodsReturnOrder in wmsGoodsReturnOrderList) 
                {
                    if (wmsGoodsReturnOrder.Id > 0)
                    {
                        if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.Add(wmsGoodsReturnOrder.Adapt<WmsGoodsReturnOrder>());
                    }
                    else 
                    {
                        adds.Add(wmsGoodsReturnOrder.Adapt<WmsGoodsReturnOrder>());
                    }
                }

                if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.ForEach(x => _wmsGoodsReturnOrderRep.Update(x));
                

                var maxId = _wmsGoodsReturnOrderRep.DetachedEntities.OrderByDescending(x => x.Id).Select(x => x.Id).FirstOrDefault();
                adds.ForEach(x => x.Id = ++maxId);    
                Db.GetDbContext().Set<WmsGoodsReturnOrder>().AddRange(adds);  
                Db.GetDbContext().SaveChanges();
               
            }
            await Task.CompletedTask;
            return adds.Count;
        }

        /// <summary>
        /// 根据版本下载退货单的Excel导入模板
        /// </summary>
        /// <param name="version">模板版本</param>
        /// <returns>下载的模板文件</returns>
        [HttpGet("downloadExcelTemplate")]
        public async Task<IActionResult> DownloadExcelTemplate([FromQuery] string version)
        {
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsGoodsReturnOrder", version);
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var path = Path.Combine(@"\", excelTemplate.TemplateFileName);
            Stream ms = FileUtil.Download(path, excelTemplate.TemplateFileName);
            var fileName = HttpUtility.UrlEncode($"{excelTemplate.Name}导入模板.xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
        /// <summary>
        /// 根据退货单查询参数导出Excel
        /// </summary>
        /// <param name="input">退货单查询参数</param>
        /// <returns>导出的Excel文件</returns>
        [HttpGet("toExcel")]
        public async Task<IActionResult> ToExcelAsync([FromQuery] WmsGoodsReturnOrderSearchNonPage input)
        {
            var wmsGoodsReturnOrderList = await ListNonPageAsync(input);
            MemoryStream ms = new();
            DataConvertUtil.ToExcelData(wmsGoodsReturnOrderList, _sysDictTypeRep, _sysDictDataRep, out List<string> headers, 
                out List<List<object>> data, out string sheetName);
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsGoodsReturnOrder", "v1");
            if (excelTemplate != null)
            {
                ExcelUtil.ToExcel(excelTemplate.TemplateFileName, headers, data, sheetName, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, ms);
            }
            else 
            {
                ExcelUtil.ToExcel(headers, data, sheetName, ms);
            }
            ms.Position = 0;
            var fileName = HttpUtility.UrlEncode($"{sheetName}[{DateTimeOffset.Now:yyyy-MM-dd}].xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
    }
}
